//
//  AddGoodsController.m
//  tuanGG
//
//  Created by 李洪旭 on 15/9/21.
//  Copyright (c) 2015年 weita. All rights reserved.
//

#import "AddGoodsController.h"
#import "AddGoodsViewCell.h"
#import "KeyboardManager.h"
@interface AddGoodsController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UITextFieldDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UIView *line;
@property (nonatomic,strong)NSArray *array;
@property (nonatomic,strong)NSMutableArray *detailArray;
@property (nonatomic,strong)UITableView *UnitTableView;
@property (nonatomic,strong)NSArray *UnitArray;
@property (nonatomic,strong)NSArray *speciesArray;
@property (nonatomic,strong)UIButton *UnitLine;
@property (assign ,nonatomic)NSInteger index;
@property (nonatomic,strong)NSMutableArray *AccordingArray;
@property (nonatomic,strong)UIDatePicker *datePicker;
@property (nonatomic,strong)NSString *SelectDate;
@property (nonatomic,strong)AddGoodsViewCell *cell;
@property (nonatomic,strong)UITextField *textField;
@property (nonatomic,strong)NSDate *localDate;//时间
@property (nonatomic,strong)NSString *state;
@property (nonatomic)BOOL addGoods;
@end

@implementation AddGoodsController
- (instancetype)init
{
    self = [super init];
    if (self) {
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveButton)];
        NSDictionary *rightTitle = @{NSFontAttributeName:[UIFont fontWithName:font_Font size:15],NSForegroundColorAttributeName:[UIColor whiteColor]};
        [rightItem setTitleTextAttributes:rightTitle forState:UIControlStateNormal];
        self.navigationItem.rightBarButtonItem = rightItem;
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated{
    _index = 0;
    [self tabBarHidden];
    if (_dictionary ==nil || [_dictionary count] == 0) {
        NSLog(@"新增商品");
        _addGoods = YES;
    }else if(_dictionary){
        NSLog(@"编辑商品");
        _addGoods = NO;
        _AccordingArray[0] = [NSString stringWithFormat:@"%ld元代金劵",[_dictionary[@"facevalue"]integerValue]];
        _AccordingArray[2] = _dictionary[@"datelimite"];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self addnavigationTitle:@"编辑代金劵" navColor:@"4fd2be"];
    [self initializedataSource];
    [self addTableView];
    
}
- (void)initializedataSource {
    _array = @[@"代金劵面值",@"代金劵购买金额(元)",@"代金劵到期时间"];
    _detailArray = [NSMutableArray arrayWithObjects:@"",@"",@"", nil];
    _AccordingArray = [NSMutableArray arrayWithObjects:@"",@"",@"", nil];
}
- (void)addTableView {
    _line = [[UIView alloc]initWithFrame:CGRectMake(50, 20, ScreenWidth-100, ScreenHeight/4)];
    _line.backgroundColor = [UIColor clearColor];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth-200, ScreenHeight/4-60)];
    lineView.backgroundColor = [UIColor whiteColor];
    lineView.center = CGPointMake(ScreenWidth/2, _line.frame.size.height/2);
    
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    image.center = CGPointMake(lineView.frame.size.width/2, lineView.frame.size.height/3);
    image.image = [UIImage imageNamed:@"Fruit_add"];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 20)];
    label.text = @"商品封面";
    label.center = CGPointMake(lineView.frame.size.width/2, lineView.frame.size.height/3*2);
    label.textColor = [UIColor colorWithWhite:0.800 alpha:1.000];
    label.textAlignment = NSTextAlignmentCenter;
    [lineView addSubview:label];
    [lineView addSubview:image];
    [_line addSubview:lineView];
    
    UIButton *addImage = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth-200, ScreenHeight/4-60)];
    addImage.backgroundColor = [UIColor clearColor];
    [addImage addTarget:self action:@selector(addImage) forControlEvents:UIControlEventTouchUpInside];
    addImage.center = CGPointMake(ScreenWidth/2, _line.frame.size.height/2);
    [_line addSubview:addImage];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-64) style:UITableViewStyleGrouped];
//    _tableView.tableHeaderView = _line;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.allowsSelectionDuringEditing = YES;
    _tableView.scrollEnabled = YES;
    _tableView.bounces = YES;
    _tableView.delaysContentTouches = YES;
    _tableView.canCancelContentTouches = YES;
    _tableView.bouncesZoom = YES;
    _tableView.userInteractionEnabled = YES;
    
    _tableView.tag = 0;
    [_tableView registerClass:[AddGoodsViewCell class] forCellReuseIdentifier:@"CELL"];
    [self.view addSubview:_tableView];
    //单位选择视图
    _UnitTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -150, ScreenWidth, 150)style:UITableViewStylePlain];
    _UnitTableView.backgroundColor = [UIColor clearColor];
    _UnitTableView.delegate = self;
    _UnitTableView.dataSource = self;
    _UnitTableView.bounces = NO;
    _UnitTableView.tag =1;
    _UnitTableView.hidden = YES;
    [_UnitTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UNIT"];
    _UnitArray = @[@"1元代金劵",@"10元代金劵",@"100元代金劵"];
    [self.view addSubview:_UnitTableView];

    _textField = [[UITextField alloc]initWithFrame:CGRectMake(ScreenWidth-180, 0, 170, 50)];
    _textField.placeholder = @"请输入代金劵购买的金额";
    if (_dictionary[@"price"]==nil) {
        _textField.text = @"";
    }else{
        _textField.text = [NSString stringWithFormat:@"%@元",_dictionary[@"price"]];
    }
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textField.textAlignment = NSTextAlignmentRight;
    _textField.font = [UIFont systemFontOfSize:14];
    [_textField setDelegate: self];

    _UnitLine = [[UIButton alloc]initWithFrame:CGRectMake(0, _UnitTableView.frame.size.height, ScreenWidth, ScreenHeight-_UnitTableView.frame.size.height)];
    _UnitLine.hidden = YES;
    _UnitLine.backgroundColor = [UIColor blackColor];
    _UnitLine.alpha = 0.3;
    [_UnitLine addTarget:self action:@selector(cancelChoose) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_UnitLine];
    
    UIView *buttonLine = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 100)];
    UIButton *nextButton = [[UIButton alloc]initWithFrame:CGRectMake(20, 50, ScreenWidth-40, 50)];
    nextButton.backgroundColor = [UIColor colorWithHexString:@"4fd2be"];
    [nextButton setTitle:@"确认上架" forState:UIControlStateNormal];
    [nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    nextButton.layer.cornerRadius = 5;
    [nextButton addTarget:self action:@selector(nextButton:) forControlEvents:UIControlEventTouchUpInside];
    [buttonLine addSubview:nextButton];
    _tableView.tableFooterView =buttonLine;


    //获取当前时间

    _datePicker = [ [ UIDatePicker alloc] initWithFrame:CGRectMake(0,ScreenHeight-64,ScreenWidth,150)];
    _datePicker.datePickerMode = UIDatePickerModeDate;
    _datePicker.backgroundColor = [UIColor whiteColor];
    [_datePicker addTarget:self action:@selector(Determine) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_datePicker];
}
#pragma mark - 事件实现

- (void)addImage {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:@"拍照"
                                                    otherButtonTitles:@"相册", nil];
    [choiceSheet showInView:self.view];
}

//退出选择商品单位
- (void)cancelChoose {

    [UIView animateWithDuration:0.2 animations:^{
        _UnitTableView.frame = CGRectMake(0, -150, ScreenWidth, 150) ;
        _datePicker.frame = CGRectMake(0, ScreenHeight-64, ScreenWidth, 150) ;
        _UnitLine.hidden = YES;
    } completion:^(BOOL finished) {
        [_tableView reloadData];
    }];


}
//进入选择商品单位
- (void)determineChoose {
    [UIView animateWithDuration:0.2 animations:^{
        _UnitLine.frame = CGRectMake(0, _UnitTableView.frame.size.height, ScreenWidth, ScreenHeight);
        _UnitTableView.hidden= NO;
        _UnitLine.hidden = NO;
        _UnitLine.tag = 1;
        _UnitTableView.frame = CGRectMake(0, 0,ScreenWidth , 150) ;
    }];
}
//保存上架商品
- (void)saveButton {
    _state = @"0";
    [self judge];
}
- (void)nextButton:(UIButton *)sender {
    _state = @"1";
    [self judge];
}
- (void)judge{
    if ([_AccordingArray[0] isEqualToString:@""]) {
        [Common addAlert:@"请选择代金劵面值"];
    }else if([_SelectDate isEqualToString:@""]){
        [Common addAlert:@"请选择代金劵到期时间"];
    }else if([_textField.text isEqualToString:@""]){
        [Common addAlert:@"请输入代金劵购买金额"];
    }else {
        [self networking];
    }
}
//进入选择日期
- (void)timeDate{
    NSDate *senddate = [NSDate date];
    if ([_SelectDate isEqualToString:@""]) {
        _datePicker.date = senddate;
    }
    _datePicker.minimumDate = senddate;
    [UIView animateWithDuration:0.2 animations:^{
    _datePicker.frame = CGRectMake(10, ScreenHeight-214, ScreenWidth-20, 150) ;
    _UnitLine.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    }completion:^(BOOL finished) {
    _UnitLine.hidden = NO;
    }];
}
//监视日期滚动
- (void)Determine{
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:_datePicker.date];
    _localDate = [_datePicker.date dateByAddingTimeInterval:interval];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    _SelectDate = [dateFormatter stringFromDate:_datePicker.date];
    _AccordingArray[2] = [NSString stringWithFormat:@"%ld", (long)[_localDate timeIntervalSince1970]];
    [_tableView reloadData];
    NSLog(@"%@",_SelectDate);
}

#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == 1) {
        return 1;
    }
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView.tag == 1) {
        return _UnitArray.count;
    }
    return _array.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView.tag == 1) {
        return 0;
    }
    return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (tableView.tag == 1) {
        return 0;
    }
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 1) {
        return 50;
    }
    return 50;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 1) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UNIT" forIndexPath:indexPath];
        if (_index == 1) {
            cell.textLabel.text = _UnitArray[indexPath.section];
            cell.textLabel.font = [UIFont systemFontOfSize:14];
        }else if (_index == 2){
            cell.textLabel.text = _speciesArray[indexPath.section];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else {
        NSInteger a= indexPath.section;
        _cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
        _cell.textLabel.text =  _array[indexPath.section];
        _cell.textLabel.font = [UIFont systemFontOfSize:14];
        _cell.textLabel.textColor = [UIColor colorWithHexString:@"383838"];
        _cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if(indexPath.section == 1){
            _textField.tag = indexPath.section;
            [_cell addSubview:_textField];
        }else if (indexPath.section == 2){
            if (_addGoods == YES) {
                _cell.label.text = _SelectDate;
            }else{
            NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
            NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[_AccordingArray[2] integerValue]];
            NSLog(@"1296035591  = %@",confromTimesp);
            [formatter setDateFormat:@"yyyy年MM月dd日"];
            _SelectDate = [formatter stringFromDate:confromTimesp];
            NSLog(@"confromTimespStr =  %@",_SelectDate);
                _cell.label.text = _SelectDate;
            }
        }else
        _cell.label.text = _AccordingArray[0];
        
        return _cell;
    }
 
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView endEditing:YES];
    if (tableView.tag == 1) {
        if (_index == 1) {

            _AccordingArray[0] = [_UnitArray[indexPath.section]mutableCopy];
            [self cancelChoose];

        }else if (_index == 2){

        [_tableView reloadData];

        }
    }else if (tableView.tag == 0){

        if (indexPath.section == 0) {

            _index = 1;
            [self determineChoose];

        }else if (indexPath.section == 2){

            [self timeDate];



        }
        [_UnitTableView reloadData];

    }
}




#pragma mark - <UIActionSheetDelegate>


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    NSLog(@"%d",textField.tag);
//    NSLog(@"%d\n,\n%d,\n%@,\n%@",range.location,range.length,string,textField.text);
    if (string.length == 0) {
        return YES;
    }
    if (string.length != 0) {
        //控制长度
        if(range.location>=20)
            return NO;

        const char * ch=[string cStringUsingEncoding:NSUTF8StringEncoding];
        if(*ch == 0)
            return YES;
        //字符0－9 和 .
        if( *ch != 46 && ( *ch<48 || *ch>57) )
            return NO;

        //有了小数点
        if([textField.text rangeOfString:@"."].length==1)
        {
            NSUInteger length=[textField.text rangeOfString:@"."].location;

            //小数点后面两位小数 且不能再是小数点
            if([[textField.text substringFromIndex:length] length]>2 || *ch ==46)   //3表示后面小数位的个数。。
                
                return NO;
        }
        
        return YES;
        
    }else {
        if (string.length >10) {
            [self addAlert:@"超出输入限制" otherButtonTitles:nil];
            return NO;
        }
    }

    return  YES;

}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.textField resignFirstResponder];

    return YES;
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
#pragma mark - 网络请求
- (void)networking {
    NSLog(@"时间：%@",_localDate);
    NSDictionary *dictionary = @{@"facevalue":[NSString stringWithFormat:@"%ld",[_AccordingArray[0]integerValue]],@"price":[NSString stringWithFormat:@"%.2f",[_textField.text floatValue]],@"datelimite":_AccordingArray[2],@"ispublish":_state};
    [GLAFRequest startRequest:good_edit_url paramsDic:dictionary defaultdialog:YES ispost:YES handleSuccess:^(id sta, NSDictionary *paramsDic) {
        NSLog(@"商品发布:%@",sta);
        if ([sta[@"code"]integerValue] == 1) {
            if ([sta[@"pramaters"][@"ispublish"][0]integerValue]==0) {
                [self addAlert:@"商品保存成功" otherButtonTitles:@"取消"];
            }else{
                [self addAlert:@"商品上架成功" otherButtonTitles:@"取消"];
            }

        }
    } doFinally:^(NSDictionary *paramsDic) {

    }];
}
@end
